<?php
/*
微信授权URL页 微信配置页填写URL为?g=wx&m=wxapi&u=$userid
用于响应微信请求与微信交互
*/
include_once(ROOTDIR.'include/wx.class.php');
class Wxapi_con extends Wx{
	public $userid;
	public function index(){
		if(empty($GLOBALS["HTTP_RAW_POST_DATA"])){
			//如果没有内容则作为微信认证服务器用
			echo $_GET["echostr"];
			exit;
		}else{
			//接收微信发送内容并解析
			$wxpost = $GLOBALS["HTTP_RAW_POST_DATA"];
			$userid=intval($_GET["u"]);
			$this->userid=$userid;
			$data = $this->xmltoarr($wxpost); 
			$wxdata["tuid"] = $data["fuid"];
			$wxdata["fuid"] = $data["tuid"];
			//$this->setdata("errortest","content='{$wxpost}',gcontent='".json_encode($_GET)."',tim=now()");
			$userinfo = $this->viewdata("*","users","where id={$this->userid}");
			//判断微信发送的内容类型
			if($data["type"]=='text'){
				//如果是文本
				//好吧，最先是判断是否是客服
				if($data["content"]=='客服'){
					$wxdata["type"]='transfer_customer_service';
					$repost = $this->wxrepost($wxdata);
					echo $repost;
					exit;
				}
				//先查找是否有相关活动
				$tempevent =json_decode($this->call_get($this->basehost."?g=user&m=activityinfo&a=returninfo&username={$userinfo['username']}&keyword=".$data["content"]),true);
				if(!empty($tempevent["item"])){
					$eventkey = array_rand($tempevent["item"]);
					$eventinfo = $tempevent["item"][$eventkey];
					
					if(!empty($eventinfo["starpicurl"])){
						//如果有图片就包成图文
						$wxdata["type"] = "news";
						$enews = array(
							0=>array("title"=>$eventinfo["name"],"digest"=>$eventinfo["info"],"url"=>$eventinfo["starpicurl"],"content_source_url"=>$eventinfo["linkcode"])
						); 
						$wxdata["news"] = $enews;
						$repost = $this->wxrepost($wxdata);
					}else{
						//如果没图片就UI福文本链接
						$wxdata["type"]="link";
						$wxdata["link"]=$eventinfo["linkcode"];
						$wxdata["content"] = $eventinfo["title"];
						$repost = $this->wxrepost($wxdata);
					}
					echo $repost;
					exit;
				}
				//查询旧版图文
				$tempimg = json_decode($this->call_get($this->basehost."?g=wx&m=getvq&key={$data['content']}&t={$userinfo['token']}"),true);
				if(!empty($tempimg)){
					$wxdata["type"]='news';
					foreach($tempimg as $k=>$v){
						$vqnews[$k]["title"] = $v["title"];
						$vqnews[$k]["digest"] = $v["text"];
						$vqnews[$k]["url"] = $v["pic"];
						$vqnews[$k]["content_source_url"] = $v["url"];
					}
					$wxdata["news"] = $vqnews;
					$repost = $this->wxrepost($wxdata);
					echo $repost;
					exit;
				}
				//如果没有活动和图文则开始匹配关键词
				$rdata = $this->getkeyxml($wxdata,$data["content"]);
				if(is_array($rdata)){
					//匹配关键词并且是全部回复的消息
					$repost = $rdata["r"];
					$txt=$rdata["txt"];
					$media=$rdata["media"];
					echo $repost;
					//剩余内容用客服接口发送
					if(!empty($txt)){
						foreach($txt as $v){
							$wxdata["content"]=$v;
							$this->sendkf($wxdata,'text');
						}
					}
					if(!empty($media)){
						foreach($media as $v){
							$view=$this->viewdata("*","wxmedia","where media_id='{$v}'");
							if($view["type"]=='img'){
								$wxdata["media_id"] = $v;
								$this->sendkf($wxdata,'image');
							}elseif($view["type"]=='voice'){
								$wxdata["media_id"] = $v;
								$this->sendkf($wxdata,'voice');
							}elseif($view["type"]=='video'){
								$wxdata["media_id"] = $v;
								$wxdata["title"]=$view["title"];
								$wxdata["desc"]=$view["content"];
								$this->sendkf($wxdata,'video');
							}elseif($view["type"]=='news'){
								$tempcontent = unserialize(base64_decode($view["content"]));
								$wxdata["newx"] = $tempcontent["articles"];
								$this->sendkf($wxdata,'news');
							}
						}
					}
				}else{
					//未匹配关键词或者是关键词随机回复的消息
					$repost = $rdata;
					echo $repost;
				}
				exit;
			}elseif($data["type"]=='event'){
				//如果是事件
				$wqeventarr=array('ShakearoundUserShake','ShakearoundLotteryBind','card_pass_check','card_not_pass_check','user_get_card','user_del_card','user_consume_card','poi_check_notify');
				if($data["event"]=='subscribe'){
					//关注事件
					$repost = $this->getsubxml($wxdata);
					echo $repost;
					exit;
				}elseif(in_array($data["event"],$wqeventarr)){
					$wqdata=$GLOBALS["HTTP_RAW_POST_DATA"];
					$wxinfo = $this->viewdata("wqid,wqtoken","wxuser","where userid={$userid}");
					$signature=$this->checkSign($wxinfo["wqtoken"],$_GET["timestamp"],$_GET["nonce"]);
					$nonce=$_GET["nonce"];
					$timestamp=$_GET["timestamp"];
					$repost = $this->call_post_wq('http://yun.zhongsou.com/api.php?id='.$wxinfo["wqid"].'&signature='.$signature.'&timestamp='.$timestamp.'&nonce='.$nonce.'&userid='.$userid,$wqdata);
					if(!empty($ret)){echo $repost;}
				}elseif($data["event"]=='poi_check_notify'){
					$poi_id = $data["poiId"];
					$result = $data["Result"];
					$msg = $data["Msg"];
					$sid=$data['UniqId'];
					if($result=='success'){
						$this->updata("wxshop","poi_id={$poi_id}","where userid={$userid} and id=$sid");
					}else{
						$this->updata("wxshop","status=1","where userid={$userid} and id=$sid");
					}
				}elseif($data["event"]=='card_pass_check'){
					$car_id=$data['CardId'];
					$this->updata("wxcard_baseinfo","card_status=0","where userid={$userid} and card_id='{$car_id}'");
				}elseif($data["event"]=='CLICK'){
					//自定义菜单事件
					$key = empty($data["eventkey"])?$data["EventKey"]:$data["eventkey"];
					if($key=='客服'){
						$wxdata["type"]='transfer_customer_service';
						$repost = $this->wxrepost($wxdata);
						echo $repost;
						exit;
					}
					$tempimg = json_decode($this->call_get($this->basehost."?g=wx&m=getvq&key={$key}&t={$userinfo['token']}"),true);
					if(!empty($tempimg)){
						$wxdata["type"]='news';
						foreach($tempimg as $k=>$v){
							$vqnews[$k]["title"] = $v["title"];
							$vqnews[$k]["digest"] = $v["text"];
							$vqnews[$k]["url"] = $v["pic"];
							$vqnews[$k]["content_source_url"] = $v["url"];
						}
						$wxdata["news"] = $vqnews;
						$repost = $this->wxrepost($wxdata);
						echo $repost;
						exit;
					}
				}
			}else{
				//其他类型用默认回复
				$repost = $this->getnormalxml($wxdata);
				echo $repost;
			}
			exit;
		}
	}
	
	//发送客服消息
	public function sendkf($wxdata,$type){
		$data["touser"] = $wxdata["tuid"];
		$data["msgtype"] = $type;
		if($type=='text'){
			$data["text"]["content"]= $wxdata["content"];
		}elseif($type=='image'){
			$data["image"]["media_id"] = $wxdata["media_id"];
		}elseif($type=='voice'){
			$data["voice"]["media_id"] = $wxdata["media_id"];
		}elseif($type=='video'){
			$data["video"]["media_id"] = $wxdata["media_id"];
			$data["video"]["title"] = $wxdata["title"];
			$data["video"]["description"] = $wxdata["desc"];
		}elseif($type=='news'){
			$data["news"]=$wxdata["news"];
		}
		$this->repost_message($data);
	}
	
	//获得关键词回复
	public function getkeyxml($wxdata,$q){
		if(empty($q)){return '';}
		$list = $this->arrdata("id","wxrequest_info","where (tkey='{$q}' and mode=0) or (locate('{$q}',tkey) and mode=1)","id asc");
		if(empty($list)){return $this->getnormalxml($wxdata);}
		$where="where userid={$this->userid} and (";
		foreach($list as $k=>$v){
			$where .=" find_in_set(tkey,'".$list[$k]["id"]."') or";
		}
		$where=trim($where,"or").")";
		$view = $this->viewdata("*","wxrequest","{$where} order by id desc");
		if(empty($view)){return $this->getnormalxml($wxdata);}
		$content = unserialize($view["content"]);
		if(!empty($content)){
			$txt=$content["txt"];
			$media=$content["media"];
		}
		if($view["mode"]==1){
			//如果勾选全部回复 
			//先回复一条
			if(!empty($txt)){
				$wxdata["type"]='text';
				$wxdata["content"] = array_shift($txt);
				$data["r"] = $this->wxrepost($wxdata);
			}elseif(!empty($media)){
				$media_id=array_shift($media);
				$data["r"] = $this->getmediainfo($wxdata,$media_id);
			}
			$data["txt"]=$txt;
			$data["media"]=$media;
			return $data;
		}else{
			//随机回复一条
			if(!empty($txt) && !empty($media)){
				$rnum=rand(1,9);
				if($rnum<6){
					$rkey = array_rand($txt);
					$rmode = 'txt';
				}else{
					$rkey = array_rand($media);
					$rmode = 'media';
				}
			}elseif(!empty($txt)){
				$rkey=array_rand($txt);
				$rmode = 'txt';
			}elseif(!empty($media)){
				$rkey=array_rand($media);
				$rmode = 'media';
			}
			if($rmode=='txt'){
				$wxdata["type"]='text';
				$wxdata["content"] = $txt[$rkey];
				return $this->wxrepost($wxdata);
			}elseif($rmode=='media'){
				return $this->getmediainfo($wxdata,$media[$rkey]);
			}
		}
	}
	
	//获取素材信息
	public function getmediainfo($wxdata,$media_id){
		$mediainfo = $this->viewdata("*","wxmedia","where media_id='{$media_id}'");
		if(empty($mediainfo)){
				$wxdata["type"]='text';
				$wxdata["content"]='获取媒体信息错误';
				return $this->wxrepost($wxdata);
		}
		if($mediainfo["type"]=='img'){
			$wxdata["type"]='image';
			$wxdata["media_id"] = $mediainfo["media_id"];
		}elseif($mediainfo["type"]=='voice'){
			$wxdata["type"]='voice';
			$wxdata["media_id"] = $mediainfo["media_id"];
		}elseif($mediainfo["type"]=='video'){
			$wxdata["type"]='video';
			$wxdata["title"]=$mediainfo["title"];
			$wxdata["desc"] = $mediainfo["content"];
			$wxdata["media_id"] = $mediainfo["media_id"];
		}elseif($mediainfo["type"]=='news'){
			$tempnews = unserialize(base64_decode($mediainfo["content"]));
			$news = $tempnews["articles"];
			if(!empty($news)){
				foreach($news as $k=>$v){
					$news[$k]["url"] = $this->oncedata("url","wxmedia","where media_id='".$news[$k]["thumb_media_id"]."'");
					if(empty($news[$k]["digest"])){
						$news[$k]["digest"] = $this->cutstr_utf8(strip_tags(str_replace("&nbsp;",' ',$news[$k]["content"])),54,'..');
					}
				}
			}
			$wxdata["type"]='news';
			$wxdata["news"] = $news;
		}
		return $this->wxrepost($wxdata);
	}
	
	
	//获得关注回复
	public function getsubxml($wxdata){
		$list = $this->arrdata("*","wxrequest","where userid={$this->userid} and type=9");
		if(empty($list)){
			return $this->getnormalxml($wxdata);
		}
		$key = array_rand($list);
		$view = $list[$key];
		if($view["mode"]==1){
			$wxdata["type"]='text';
			$wxdata["content"] = $view["content"];
			return $this->wxrepost($wxdata);
		}else{
			return $this->getmediainfo($wxdata,$view["content"]);
		}
	}
	
	//获得默认回复
	public function getnormalxml($wxdata){
		$list = $this->arrdata("*","wxrequest","where userid={$this->userid} and type=8");
		if(empty($list)){
			$wxdata["type"]='text';
			$wxdata["content"]='虽然你很想表达什么，但是我不太明白';
			return $this->wxrepost($wxdata);
		}
		$key = array_rand($list);
		$view = $list[$key];
		if($view["mode"]==1){
			$wxdata["type"]='text';
			$wxdata["content"] = $view["content"];
			return $this->wxrepost($wxdata);
		}else{
			return $this->getmediainfo($wxdata,$view["content"]);
		}
	}
	
	
	public function wxcallback(){
		
	}
}